/**
 * @title: SystemRuleMysqlDataSource
 * @projectName mscloud
 * @Description TODO
 * @Author
 * @Date 2022/2/22 20:41
 */
package com.atguigu.springcloud.cloudsentinelgatewaydevelop.sentinel.datasource;

import com.alibaba.csp.sentinel.datasource.AutoRefreshDataSource;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.bean.dto.SentinelSystemRuleDTO;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.sentinel.convert.impl.SystemRuleMysqlConverter;
import com.atguigu.springcloud.cloudsentinelgatewaydevelop.service.SystemRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.List;
@Component
public class SystemRuleMysqlDataSource extends AutoRefreshDataSource<List<SentinelSystemRuleDTO>, List<SystemRule>> {
    @Value("${spring.application.name}")
    String applicationName;
    @Autowired
    SystemRuleService systemRuleService;
    public SystemRuleMysqlDataSource(SystemRuleMysqlConverter systemRuleMysqlConverter){
        super(systemRuleMysqlConverter,systemRuleMysqlConverter.getRecommendRefreshMs());
    }
    @PostConstruct
    public void init() {
        try {
            List<SystemRule> newValue = loadConfig();
            getProperty().updateValue(newValue);
        } catch (Throwable e) {
            RecordLog.info("RuleMysqlDataSource loadConfig exception", e);
        }
    }
    @Override
    public List<SentinelSystemRuleDTO> readSource() throws Exception {
        Flux<SentinelSystemRuleDTO> byApplicationName = systemRuleService.findByApplicationName(applicationName);
        Mono<List<SentinelSystemRuleDTO>> listMono = byApplicationName.collectList();
        return listMono.block();
    }
}
